import axios from 'axios';

// 创建axios实例
const apiClient = axios.create({
  baseURL: '/api', // 与vite.config.js中的代理配置对应
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    // 可以在这里添加token等认证信息
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    // 统一处理响应格式
    if (response.data && (response.data.code === 200 || response.data.code === '0')) {
      return response.data;
    } else {
      throw new Error(response.data?.message || '请求失败');
    }
  },
  error => {
    console.error('API请求错误:', error);
    // 可以在这里统一处理错误
    return Promise.reject(error);
  }
);

// API调用包装器，支持失败时回退到模拟数据
const apiCallWithFallback = async (apiFunction, fallbackFunction, ...args) => {
  try {
    // 尝试调用实际API
    const result = await apiFunction(...args);
    return result;
  } catch (error) {
    console.log('API调用失败，使用模拟数据:', error.message);
    // 回退到模拟数据
    return fallbackFunction(...args);
  }
};

// 统一错误处理
const handleError = (error) => {
  console.error('API请求错误:', error);
  throw {
    code: 500,
    message: error.message || '请求失败，请稍后重试',
    data: null,
    timestamp: Date.now()
  };
};

// 检查后端连接状态
export const checkBackendConnection = async () => {
  try {
    const response = await apiClient.get('/health');
    return {
      connected: response.code === 200 || response.code === '0',
      message: '连接成功'
    };
  } catch (error) {
    console.error('后端连接检查失败:', error);
    return {
      connected: false,
      message: error.message || '后端服务未启动'
    };
  }
};

// 模拟数据
const mockData = {
  characters: [
    {
      charId: 1,
      name: '李白',
      description: '唐代伟大的浪漫主义诗人，被誉为"诗仙"，其诗歌风格豪放飘逸，想象力丰富。',
      avatarUrl: null,
      avatarColor: '#FF6B6B',
      title: '诗仙',
      voiceStyle: 'elegant'
    },
    {
      charId: 2,
      name: '诸葛亮',
      description: '字孔明，号卧龙，三国时期蜀汉丞相，杰出的政治家、军事家、外交家。',
      avatarUrl: null,
      avatarColor: '#1D3557',
      title: '三国军师',
      voiceStyle: 'wise'
    },
    {
      charId: 3,
      name: '爱因斯坦',
      description: '现代物理学的开创者和奠基人，提出相对论，改变了人类对宇宙的认识。',
      avatarUrl: null,
      avatarColor: '#457B9D',
      title: '物理学家',
      voiceStyle: 'knowledgeable'
    },
    {
      charId: 4,
      name: '居里夫人',
      description: '首位获得两次诺贝尔奖的科学家，在放射性研究领域做出了开创性贡献。',
      avatarUrl: null,
      avatarColor: '#A8DADC',
      title: '科学家',
      voiceStyle: 'wise'
    },
    {
      charId: 5,
      name: '贝多芬',
      description: '德国作曲家和钢琴家，维也纳古典乐派代表人物之一，世界音乐史上的巨人。',
      avatarUrl: null,
      avatarColor: '#F1FAEE',
      title: '作曲家',
      voiceStyle: 'poetic'
    },
    {
      charId: 6,
      name: '孔子',
      description: '名丘，字仲尼，春秋时期伟大的思想家、教育家，儒家学派创始人。',
      avatarUrl: null,
      avatarColor: '#2A9D8F',
      title: '思想家',
      voiceStyle: 'wise'
    }
  ],
  historySessions: [
    {
      convId: 5001,
      charId: 1,
      characterName: '李白',
      characterAvatar: null,
      title: '关于唐诗的探讨',
      messageCount: 12,
      lastUpdateTime: Date.now() - 3600000 // 1小时前
    },
    {
      convId: 5002,
      charId: 3,
      characterName: '爱因斯坦',
      characterAvatar: null,
      title: '相对论的基本原理',
      messageCount: 18,
      lastUpdateTime: Date.now() - 7200000 // 2小时前
    },
    {
      convId: 5003,
      charId: 2,
      characterName: '诸葛亮',
      characterAvatar: null,
      title: '三国历史讨论',
      messageCount: 25,
      lastUpdateTime: Date.now() - 86400000 // 1天前
    }
  ],
  sessionMessages: {
    5001: [
      {
        msgId: 8001,
        convId: 5001,
        role: 'USER',
        contentType: 'TEXT',
        content: '李白你好，能给我背一首你的诗吗？',
        audioUrl: null,
        timestamp: Date.now() - 3600000
      },
      {
        msgId: 8002,
        convId: 5001,
        role: 'assistant',
        contentType: 'TEXT',
        content: '床前明月光，疑是地上霜。举头望明月，低头思故乡。',
        audioUrl: null,
        timestamp: Date.now() - 3500000
      },
      {
        msgId: 8003,
        convId: 5001,
        role: 'USER',
        contentType: 'TEXT',
        content: '这首诗表达了什么情感？',
        audioUrl: null,
        timestamp: Date.now() - 3400000
      }
    ]
  }
};

// 获取角色列表 - 实际API调用
export const getCharacterList = async (page = 0, size = 20) => {
  const actualApiCall = async () => {
    return await apiClient.get('/characters', {
      params: { page, size }
    });
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 计算分页
    const start = page * size;
    const end = start + size;
    const paginatedCharacters = mockData.characters.slice(start, end);
    
    return {
      code: 200,
      message: '成功',
      data: {
        content: paginatedCharacters,
        page,
        size,
        totalElements: mockData.characters.length,
        totalPages: Math.ceil(mockData.characters.length / size)
      },
      timestamp: Date.now()
    };
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};

// 基于后端规范的聊天接口（GET /chat/add，流式text/html响应）
// 使用浏览器 fetch + ReadableStream 读取增量文本；支持 onChunk 回调
export const chatAdd = async ({ role = undefined, prompt, chatId, onChunk }) => {
  // 参数校验
  if (!prompt || !chatId) {
    const err = new Error('参数错误：chatId 和 prompt 为必填');
    console.error('[chatAdd] 参数校验失败', { role, prompt, chatId });
    throw err;
  }

  try {
    // 组合URL（基于前端代理到 /api）
    const url = new URL('/api/chat/add', window.location.origin);
    url.searchParams.set('prompt', prompt);
    url.searchParams.set('chatId', chatId);
    if (role) url.searchParams.set('role', role);

    const response = await fetch(url.toString(), {
      method: 'GET',
      headers: {
        // 明确声明希望接收文本流
        'Accept': 'text/html;charset=utf-8'
      }
    });

    if (!response.ok) {
      const err = new Error(`请求失败：${response.status} ${response.statusText}`);
      console.error('[chatAdd] 网络错误', err);
      throw err;
    }
    if (!response.body) {
      const err = new Error('响应不支持流式读取');
      console.error('[chatAdd] 响应体为空或不可读');
      throw err;
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let aggregated = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      const chunk = decoder.decode(value, { stream: true });
      aggregated += chunk;
      if (typeof onChunk === 'function') {
        try { onChunk(chunk); } catch (cbErr) { console.warn('[chatAdd] onChunk 回调异常', cbErr); }
      }
    }

    return {
      code: 200,
      message: '成功',
      data: aggregated,
      timestamp: Date.now()
    };
  } catch (error) {
    console.error('[chatAdd] 接口异常：', error);
    // 前端抛出统一错误，后端会以 BusinessException(ErrorCode.OPERATION_ERROR) 标准化
    throw error;
  }
};

// 获取角色详情 - 实际API调用
export const getCharacterDetail = async (charId) => {
  const actualApiCall = async () => {
    return await apiClient.get(`/characters/${charId}`);
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const character = mockData.characters.find(c => c.charId === charId);
    
    if (character) {
      return {
        code: 200,
        message: '成功',
        data: character,
        timestamp: Date.now()
      };
    } else {
      return {
        code: 404,
        message: '角色不存在',
        data: null,
        timestamp: Date.now()
      };
    }
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};

// 搜索角色 - 实际API调用
export const searchCharacters = async (keyword) => {
  const actualApiCall = async () => {
    return await apiClient.get('/characters/search', {
      params: { keyword }
    });
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    if (!keyword) {
      return {
        code: 200,
        message: '成功',
        data: [],
        timestamp: Date.now()
      };
    }
    
    const lowerKeyword = keyword.toLowerCase();
    const filtered = mockData.characters.filter(character => 
      character.name.toLowerCase().includes(lowerKeyword) ||
      character.description.toLowerCase().includes(lowerKeyword) ||
      character.title.toLowerCase().includes(lowerKeyword)
    );
    
    return {
      code: 200,
      message: '成功',
      data: filtered,
      timestamp: Date.now()
    };
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};

// 获取历史记录列表 - 实际API调用
export const getHistorySessions = async (userId, page = 0, size = 20) => {
  const actualApiCall = async () => {
    return await apiClient.get('/history', {
      params: { userId, page, size }
    });
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 计算分页
    const start = page * size;
    const end = start + size;
    const paginatedSessions = mockData.historySessions.slice(start, end);
    
    return {
      code: 200,
      message: '成功',
      data: {
        content: paginatedSessions,
        page,
        size,
        totalElements: mockData.historySessions.length,
        totalPages: Math.ceil(mockData.historySessions.length / size)
      },
      timestamp: Date.now()
    };
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};

// 获取对话详情消息记录 - 实际API调用
export const getSessionMessages = async (convId) => {
  const actualApiCall = async () => {
    return await apiClient.get(`/history/${convId}/messages`);
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const messages = mockData.sessionMessages[convId] || [];
    
    return {
      code: 200,
      message: '成功',
      data: messages,
      timestamp: Date.now()
    };
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};

// 删除对话记录 - 实际API调用
export const deleteSession = async (convId) => {
  const actualApiCall = async () => {
    return await apiClient.delete(`/history/${convId}`);
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    // 在实际应用中，这里会调用后端API删除数据
    // 这里只是模拟成功响应
    
    return {
      code: 200,
      message: '对话记录删除成功',
      data: null,
      timestamp: Date.now()
    };
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};

export const transcribeAudio = async (audioBlob) => {
  
  const actualApiCall = async () => {
    // 七牛云API配置
    const API_KEY = 'YOUR_QINIU_AI_API_KEY'; // 需要替换为实际的API Key
    const API_ENDPOINT = 'https://openai.qiniu.com/v1/voice/asr';
    
    // 获取音频URL（模拟）
    const audioUrl = await getAudioUrl();
    
    // 构建请求体
    const requestBody = {
      model: 'asr',
      audio: {
        format: 'wav', // 假设音频格式为wav
        url: audioUrl
      }
    };
    
    // 直接使用fetch调用七牛云API，因为需要自定义请求头
    const response = await fetch(API_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      body: JSON.stringify(requestBody)
    });
    
    const data = await response.json();
    
    // 处理七牛云API响应格式，转换为我们应用需要的格式
    return {
      code: response.ok ? 200 : 500,
      message: response.ok ? '成功' : '失败',
      data: {
        text: data.data?.result?.text || '',
        confidence: 0.95 // 七牛云API可能不直接返回置信度，这里使用固定值
      },
      timestamp: Date.now()
    };
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 模拟语音转文本结果
    const mockTranscriptions = [
      '你好，我想了解更多关于这个项目的信息。',
      '请问你能帮我解答一个问题吗？',
      '我对AI技术非常感兴趣。',
      '这个功能看起来很有用。',
      '谢谢你的帮助。'
    ];
    
    // 随机选择一个模拟结果
    const randomIndex = Math.floor(Math.random() * mockTranscriptions.length);
    
    return {
      code: 200,
      message: '成功',
      data: {
        text: mockTranscriptions[randomIndex],
        confidence: 0.95
      },
      timestamp: Date.now()
    };
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};

// 获取音色列表 - 七牛云TTS API调用
export const getVoiceList = async () => {
  const actualApiCall = async () => {
    // 七牛云API配置
    const API_KEY = 'YOUR_QINIU_AI_API_KEY'; // 需要替换为实际的API Key
    const API_ENDPOINT = 'https://openai.qiniu.com/v1/voice/tts/voices'; // 七牛云获取音色列表接口
    
    // 直接使用fetch调用七牛云API
    const response = await fetch(API_ENDPOINT, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      }
    });
    
    const data = await response.json();
    
    // 处理七牛云API响应格式
    return {
      code: response.ok ? 200 : 500,
      message: response.ok ? '成功' : '失败',
      data: data.data?.voices || [],
      timestamp: Date.now()
    };
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 模拟音色列表数据
    const mockVoices = [
      { voice_id: 'male_1', name: '男声1', gender: 'male', language: 'zh' },
      { voice_id: 'male_2', name: '男声2', gender: 'male', language: 'zh' },
      { voice_id: 'female_1', name: '女声1', gender: 'female', language: 'zh' },
      { voice_id: 'female_2', name: '女声2', gender: 'female', language: 'zh' },
      { voice_id: 'child_1', name: '童声1', gender: 'neutral', language: 'zh' }
    ];
    
    return {
      code: 200,
      message: '成功',
      data: mockVoices,
      timestamp: Date.now()
    };
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};

// 发送消息 - 实际API调用
export const sendMessage = async (charId, content, audioUrl = null) => {
  const actualApiCall = async () => {
    return await apiClient.post('/chat/send', {
      charId,
      content,
      audioUrl
    });
  };
  
  const mockApiCall = async () => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 生成模拟响应
    let mockResponse = "";
    const character = mockData.characters.find(c => c.charId === charId);
    
    if (character) {
      // 根据不同角色生成不同的响应
      switch (character.charId) {
        case 1: // 李白
          mockResponse = "很高兴与你讨论诗歌！你的问题很有深度。";
          break;
        case 2: // 诸葛亮
          mockResponse = "我需要仔细思考一下这个问题...从战略角度来看，我认为...";
          break;
        case 3: // 爱因斯坦
          mockResponse = "这个问题涉及到相对论的基本原理。让我用简单的方式解释一下...";
          break;
        case 4: // 居里夫人
          mockResponse = "科学研究需要耐心和毅力。根据我的经验，我建议...";
          break;
        case 5: // 贝多芬
          mockResponse = "音乐是灵魂的语言。在我的作品中，我试图表达...";
          break;
        case 6: // 孔子
          mockResponse = "三人行，必有我师焉。关于这个问题，我认为...";
          break;
        default:
            mockResponse = "感谢你的提问！这是一个很有趣的话题。";
        }
    } else {
      mockResponse = "我收到了你的消息，让我思考一下如何回答...";
    }
    
    return {
      code: 200,
      message: '成功',
      data: {
        msgId: Date.now(),
        content: mockResponse,
        contentType: 'TEXT',
        role: 'assistant',
        audioUrl: null,
        timestamp: Date.now()
      },
      timestamp: Date.now()
    };
  };
  
  return apiCallWithFallback(actualApiCall, mockApiCall);
};